package com.pingan.pastry;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.pingan.pastry.entity.ResponseData;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
public class AppDispatchController {

    private Gson GSON = new Gson();

    @RequestMapping("dmpf/app/**")
    @ResponseBody
    public Object dispatch(HttpServletRequest request, HttpServletResponse response) {
        /**
         * todo 
         *  1:参数绑定,获取uri
         *  2.查询invoker
         *  3:调用invoker
         */
        ResponseData responseData = new ResponseData(0);

        String uri = request.getRequestURI();

        //获取invoker
        Invoker invoker = InvokerBucket.findInvoker(uri);
        //参数绑定
        Request param = createRequest(invoker, request);
        try {
            Object resp = invoker.invoke(param);
            responseData.setData(resp);
        } catch (Exception e) {
            System.out.println("exception in biz," + e.getMessage());
            processException(responseData, e);
        }
        return responseData;
    }

    private Request createRequest(Invoker invoker, HttpServletRequest request) {
        Class<?> requestType = invoker.getRequestType();
        Map<String, String[]> parameterMap = request.getParameterMap();
        JsonObject jsonObject = new JsonObject();
        for (String key : parameterMap.keySet()) {
            System.out.println("key:" + key + "==value:" + parameterMap.get(key));
            jsonObject.addProperty(key, parameterMap.get(key)[0]);
        }
        return (Request) GSON.fromJson(jsonObject, requestType);
    }

    private void processException(ResponseData response, Exception e) {
        response.setCode(1);
        response.setMsg(e.getMessage());
    }
}
